package com.virtualmall.controller;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
//import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.virtualmall.bean.Account;
import com.virtualmall.bean.Address;
import com.virtualmall.common.Constants;
import com.virtualmall.service.AddressService;

@Controller
@RequestMapping("/address")
public class AddressController {

    //private Logger logger = Logger.getLogger(AddressController.class);

    @Autowired
    private AddressService addressService;
    
    @RequestMapping(value="/detail",method=RequestMethod.GET)
    @ResponseBody
    public Map<String,Object> show(Address address,HttpServletRequest request){
        //logger.info("show() method begin...");

        Map<String,Object> result = new HashMap<String,Object>();
        
        try {
            Long addressId = ((Account)request.getSession().getAttribute(Constants.USER_ACCOUNT_SESSION)).getAddress().getId();
            
            address = this.addressService.read(addressId);
            
            result.put("address", address);
            result.put("result", Constants.SUCCESS_RESULT_FLAG);
        } catch (Exception e) {
            //logger.error("show() method error...",e);
            
            result.put("result", Constants.FAILURE_RESULT_FLAG);
        }
        
        //logger.info("show() method end...");

        return result;
    }
    
    @RequestMapping(value="/update",method=RequestMethod.POST)
    @ResponseBody
    public Map<String,String> update(Address address){
        //logger.info("update() method begin...");

        Map<String,String> result = new HashMap<String,String>();
        
        try {
            String tel = StringUtils.removeStart(address.getTel(), "-");
            tel = StringUtils.removeEnd(tel, "-");
            address.setTel(tel);
            
            this.addressService.update(address);
            
            result.put("result", Constants.SUCCESS_RESULT_FLAG);
        } catch (Exception e) {
            //logger.error("update() method error...",e);
            
            result.put("result", Constants.FAILURE_RESULT_FLAG);
        }
        
        //logger.info("update() method end...");

        return result;
    }
}
